package srx.open.com.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.baidu.location.BDLocation;

import org.apache.commons.lang.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.datatype.BmobGeoPoint;
import cn.bmob.v3.listener.FindListener;
import de.greenrobot.event.EventBus;
import srx.open.com.R;
import srx.open.com.activity.AddrActivity;
import srx.open.com.activity.CourseDetailedInfoActivity;
import srx.open.com.activity.SearchInfoActivity;
import srx.open.com.adapter.HomeRecommendAdpter;
import srx.open.com.bean.CoursePublish;
import srx.open.com.mode.AddrItem;
import srx.open.com.utils.Constants;
import srx.open.com.utils.Log;
import srx.open.com.utils.OpenToast;
import srx.open.com.views.RefreshListView;

/**
 * 家教首页界面
 *
 * @author hailongqiu 356752238@qq.com
 */
public class TutorFragment extends BaseFragment {

    private static final String TAG = "TutorFragment";

    /* 标题栏 */
    @Bind(R.id.home_head_location_lay)
    View home_head_location_lay;
    @Bind(R.id.home_head_city_tv)
    TextView home_head_city_tv;
    @Bind(R.id.home_head_baddr_tv)
    TextView home_head_baddr_tv;
    @Bind(R.id.home_head_search_lay)
    View home_head_search_lay;

    /* 推荐 */
    @Bind(R.id.home_progress)
    ProgressBar home_progress;
    @Bind(R.id.pull_refresh_list)
    RefreshListView pull_refresh_list;

    SearchDataMode mSearchDataMode;
    HomeRecommendAdpter mHomeRecommendAdpter;
    List<CoursePublish> mPubList = new ArrayList<CoursePublish>();

    private ArrayList<AddrItem> addrItemLists = new ArrayList<AddrItem>() {
        {
            add(new AddrItem()); // addr1 比如 四川省
            add(new AddrItem()); // addr2 比如 成都市
            add(new AddrItem()); // addr3 比如 武侯区
        }
    };

    public static TutorFragment newInstance(String s) {
        TutorFragment tutorFragment = new TutorFragment();
        return tutorFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tutor, container, false);
        ButterKnife.bind(this, view);
        initAllViews();
        return view;
    }

    @Override
    public void initAllDatas() {
        EventBus.getDefault().register(this); // 注册事件.
        mSearchDataMode = new SearchDataMode();
    }

    private View tutor_one_lay;  // 中小学/学前
    private View tutor_two_lay;  // 工作/生活/艺术
    private View tutor_three_lay;  // 兴趣帮

    private void initAllViews() {
        // 添加头信息.
        final View mHeadView = View.inflate(mContext, R.layout.include_home_head_info,
                null);
        tutor_one_lay = mHeadView.findViewById(R.id.tutor_one_lay); // 中小学/学前
        tutor_two_lay = mHeadView.findViewById(R.id.tutor_two_lay); // 工作/生活/艺术
        tutor_three_lay = mHeadView.findViewById(R.id.tutor_three_lay); // 兴趣帮
        tutor_one_lay.setOnClickListener(mHeadViewOnclick);
        tutor_two_lay.setOnClickListener(mHeadViewOnclick);
        tutor_three_lay.setOnClickListener(mHeadViewOnclick);
        //
        ListView.LayoutParams params = new ListView.LayoutParams(ListView.LayoutParams.MATCH_PARENT, mHeadView.getMeasuredHeight());
        mHeadView.setLayoutParams(params);
        pull_refresh_list.addHeaderView(mHeadView, null, false);
        //
        initPullRefreshListView();
    }

    OnClickListener mHeadViewOnclick = new OnClickListener(){
        @Override
        public void onClick(View v) {
            int id = v.getId();
            switch (id) {
                case R.id.tutor_one_lay:
                    OpenToast.showMsg("功能正在开发中... ...");
                    break;
                case R.id.tutor_two_lay:
                    OpenToast.showMsg("功能正在开发中... ...");
                    break;
                case R.id.tutor_three_lay:
                    OpenToast.showMsg("功能正在开发中... ...");
                    break;
            }
        }
    };

    private void initPullRefreshListView() {
        //
        pull_refresh_list.setPageSize(Constants.LIMIT_PAGE_NUM);
        mHomeRecommendAdpter = new HomeRecommendAdpter(mContext, mPubList,
                mDataBaseHelper);
        pull_refresh_list.setAdapter(mHomeRecommendAdpter);
        // 连接item单击事件.
        pull_refresh_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // 查看课程的详细信息.
                CoursePublish coursePublish = mPubList.get(position - 2);
                Log.d(TAG, "position:" + position + "点击查看课程详情:" + coursePublish.toString());
                Intent intent = new Intent(mContext,
                        CourseDetailedInfoActivity.class);
                intent.putExtra("CoursePublish", coursePublish);
                startActivity(intent);
            }
        });
        // 加载更多.
        pull_refresh_list.setOnLoadListener(new RefreshListView.OnLoadListener() {
            @Override
            public void onLoad() {
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        restartUpdateData(UP_PULL_STATE_UPDATE);
                    }
                }).start();
            }
        });
        // 刷新
        pull_refresh_list.setOnRefreshListener(new RefreshListView.OnRefreshListener() {
            @Override
            public void toRefresh() {
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            Thread.sleep(1500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        restartUpdateData(DOWN_PULL_STATE_UPDAE);
                    }
                }).start();
            }
        });

    }

    @OnClick(R.id.home_head_location_lay)
    void homeHeadLocationLayOnClick(View view) {
//		openActivity(AddrActivity.class);
        Intent intent = new Intent(mContext, AddrActivity.class);
        intent.putExtra("selectAddr", home_head_city_tv.getText());
        startActivityForResult(intent, AddrActivity.RESULT_ADDR_STATE);
    }

    // 弹出搜索界面.
    @OnClick(R.id.home_head_search_lay)
    void home_head_search_lay(View view) {
        Intent intent = new Intent(mContext, SearchInfoActivity.class);
        intent.putExtra("search", home_head_city_tv.getText());
        startActivityForResult(intent, SearchInfoActivity.RESULT_SEARCH_STATE);
        getActivity().overridePendingTransition(R.anim.in_from_right, R.anim.out_from_left);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null)
            return;
        Bundle b = data.getExtras();
        switch (resultCode) {
            case AddrActivity.RESULT_ADDR_STATE: // 地区返回值.
                if (b == null)
                    return;
                // addr3 比如武侯区
                String str3 = b.getString("addr3");
                int id3 = b.getInt("id3");
                AddrItem addr3 = new AddrItem(id3, str3);
                addrItemLists.set(2, addr3);
                // addr2 比如 成都市
                String str2 = b.getString("addr2");
                int id2 = b.getInt("id2");
                AddrItem addr2 = new AddrItem(id2, str2);
                addrItemLists.set(1, addr2);
                // addr1 比如 四川省
                String str1 = b.getString("addr1");
                int id1 = b.getInt("id1");
                AddrItem addr1 = new AddrItem(id1, str1);
                addrItemLists.set(0, addr1);
                // 显示最后选择的地区.
                String selectAddr = b.getString("selectAddr");
                home_head_city_tv.setText("");
                home_head_baddr_tv.setText("");
                if (!StringUtils.isEmpty(str1)) { // 判断 四川省.
                    home_head_city_tv.setText(str1);
                    if (!StringUtils.isEmpty(str2)) { // 再判断成都市.
                        home_head_baddr_tv.setText(str2);
                        if (!StringUtils.isEmpty(str3)) { // 在判断武侯区.
                            home_head_city_tv.setText(str2);
                            home_head_baddr_tv.setText(str3);
                        }
                    }
                } else {
                    home_head_city_tv.setText("未知");
                    home_head_baddr_tv.setText("未知");
                }
                // 更新数据.
                restartUpdateData(DOWN_PULL_STATE_UPDAE);
                break;
        }
    }

    /**
     * 接收定位更新的事件.
    */
    public void onEvent(BDLocation location) {
        // 精度和维度.
        double longitude = location.getLongitude();
        double latitude = location.getLatitude();
        // 详细地址.
        String lbsAddr = location.getAddrStr();
        //
        String province = location.getProvince(); // 比如: 四川省
        String city = location.getCity(); // 成都市
        String district = location.getDistrict(); // 武侯区
        //
        BmobGeoPoint tempBmobGeoPoint = new BmobGeoPoint(longitude, latitude);
        // 更新定位就保存 地区的信息.(主要用于课程发布)
        mSrxApplication.locationProvinceItem = mDataBaseHelper.queryLocationProvinceId(province);
        Log.w(TAG + " " + province + " update provinceItem id:" + mSrxApplication.locationProvinceItem.getId());
        mSrxApplication.locationCityItem = mDataBaseHelper.queryLocationCityId(city);
        Log.w(TAG + " " + city + " update cityItem id:" + mSrxApplication.locationCityItem.getId());
        mSrxApplication.locationDistrictItem = mDataBaseHelper.queryLocationDistrictId(district);
        // 第一次更新界面上的位置.
        if (mSearchDataMode.bmobGeoPoint == null) {
            // 保存定位信息.
            mSearchDataMode.bmobGeoPoint = tempBmobGeoPoint;
            // 更新地址.
            if (!TextUtils.isEmpty(lbsAddr) && !TextUtils.isEmpty(district)) {
                String addr = lbsAddr.substring(lbsAddr.indexOf(district) + district.length());
                home_head_baddr_tv.setText("" + addr);
            }
            if (!TextUtils.isEmpty(city)) {
                home_head_city_tv.setText(city);
            }
            //
            addrItemLists.set(0, mSrxApplication.locationProvinceItem);
            addrItemLists.set(1, mSrxApplication.locationCityItem);
            addrItemLists.set(2, mSrxApplication.locationDistrictItem);
            // 更新数据.
            restartUpdateData(DOWN_PULL_STATE_UPDAE);
        }
        Log.w(TAG + " " + district + " update districtItem id:" + mSrxApplication.locationDistrictItem.getId());
        // 保存定位信息，用于发布需求, 附近查询.
        mSrxApplication.locationBmobGeoPoint = tempBmobGeoPoint;
        //
        mSearchDataMode.bmobGeoPoint = tempBmobGeoPoint;
    }

    private void restartUpdateData(final int updateState) {
        queryTutorCourse(updateState);
    }

    private boolean isFirst = true;

    private void setFirstLoadDataViewShow() {
        if (isFirst) {
            home_progress.setVisibility(View.GONE);
            pull_refresh_list.setVisibility(View.VISIBLE);
            isFirst = false;
        }
    }

    /**
     * 首页查询设定.
     */
    private void queryTutorCourse(final int updateState) {
        // 刷新.
        if (updateState == DOWN_PULL_STATE_UPDAE) {
            mSearchDataMode.mSkipPageNum = 0;
        }
        BmobQuery<CoursePublish> bmobQuery = new BmobQuery<CoursePublish>();
        bmobQuery.include("usertt"); // 获取这个发布课程的老师.
        bmobQuery.order("-createdAt"); // 降序.
        bmobQuery.setSkip(mSearchDataMode.mSkipPageNum);
        bmobQuery.setLimit(Constants.LIMIT_PAGE_NUM);
        /////////////////////地区//////////////////////////
        if (addrItemLists.get(0).getId() != -1) { // 比如:北京，四川，重庆
            bmobQuery.addWhereEqualTo("provinceId", addrItemLists.get(0).getId());
            if (addrItemLists.get(1).getId() != -1) { //  比如: 成都市
                bmobQuery.addWhereEqualTo("cityId", addrItemLists.get(1).getId());
                if (addrItemLists.get(2).getId() != -1) { // 比如: 武侯区
                    bmobQuery.addWhereEqualTo("districtId", addrItemLists.get(2).getId());
                }
            }
        }
        ///////////////////分类///////////////////////////
        // 如果分类一为-1. 代表全部.
        // 如果分类二为-1.使用分类一作为基准.
        // 如果分类三为-1.使用分类一，二作为基准.
        // 分类一
        if (mSearchDataMode.oneId != -1) {
            bmobQuery.addWhereEqualTo("oneId", mSearchDataMode.oneId);
            // 分类二
            if (mSearchDataMode.twoId != -1) {
                bmobQuery.addWhereEqualTo("twoId", mSearchDataMode.twoId);
                // 分类三
                if (mSearchDataMode.threeId != -1) {
                    bmobQuery.addWhereEqualTo("threeId", mSearchDataMode.threeId);
                }
            }
        }
        ////////////////////时间(只获取前三天的数据[包含今天])////////////////////////////////
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(cal.DAY_OF_MONTH, -3);
        //
        // 这是查询r日期之后的数据 07.19, 07.20 --> 07.29
        Log.i(TAG + " 3天前的时间:" + cal.getTime().toString());
        bmobQuery.addWhereGreaterThan("createdAt", new BmobDate(cal.getTime()));
        //
        bmobQuery.findObjects(mContext, new FindListener<CoursePublish>() {

            @Override
            public void onSuccess(List<CoursePublish> pubList) {
                Log.w(TAG + " 获取推荐课程:" + pubList.size());
                if (pubList.size() > 0) {
                    if (updateState == DOWN_PULL_STATE_UPDAE) { // 下拉刷新.
                        mPubList = pubList;
                    } else { // 上啦加载更多.
                        mPubList.addAll(pubList);
                    }
                    mSearchDataMode.mSkipPageNum += pubList.size();
                    mHomeRecommendAdpter.setPubList(mPubList);
                } else {
                    OpenToast.showMsg("推荐课程已无");
                    if (updateState == DOWN_PULL_STATE_UPDAE) { // 下拉刷新.
                        mPubList.clear();
                        mHomeRecommendAdpter.setPubList(mPubList);
                    }
                }
                // 刷新.
                if (updateState == DOWN_PULL_STATE_UPDAE) {
                    pull_refresh_list.onRefreshComplete();
                } else {
                    pull_refresh_list.onLoadComplete();
                }
                pull_refresh_list.setResultSize(pubList.size());
                setFirstLoadDataViewShow();
            }

            @Override
            public void onError(int code, String msg) {
                Log.e(TAG + " code:" + code + " msg:" + msg);
                OpenToast.showMsg(msg);
                // 刷新.
                if (updateState == DOWN_PULL_STATE_UPDAE) {
                    pull_refresh_list.onRefreshComplete();
                } else {
                    pull_refresh_list.onLoadComplete();
                }
                setFirstLoadDataViewShow();
            }
        });
    }

    /*
     * 搜索的关键字类.
     */
    public class SearchDataMode {
        public int oneId = -1; // 一级分类ID.
        public int twoId = -1; // 二级分类ID.
        public int threeId = -1; // 三级分类ID.

        public int provinceId = -1; // 比如:北京，四川，重庆
        public int cityId = -1; //  比如: 成都市
        public int districtId = -1; // 比如: 武侯区

        public double kmRadio = 0.5; // 0.5[500米]，1[1公里]依次类推... ...(3km,5km)
        public BmobGeoPoint bmobGeoPoint = null;
        public int mSkipPageNum = 0; // 翻页.

        @Override
        public String toString() {
            String location = "";
            if (bmobGeoPoint != null)
                location += bmobGeoPoint.getLongitude() + ":"
                        + bmobGeoPoint.getLatitude();
            return "oneId:" + oneId + " twoId:" + twoId + " threeId:" + threeId
                    + " location:" + location + " provinceId:" + provinceId
                    + " cityId:" + cityId + " districtId:" + districtId;
        }
    }

}
